'use strict';
angular.module('clientApp')
.directive('modifierpanneau', function($filter, flightAPI, ngToast, panelAPI) {
    return {
        restrict : 'E',
        scope : {
        	panneau : '=',
            added : '=',
            view : '='
        },
        link : function($scope) {
			$scope.sendFormat = 'HH-mm';
			$scope.hstep = 1;
			$scope.mstep = 1;
			$scope.ismeridian = false;
			$scope.IHeure = new Date();
			
			$scope.selected = null;
			$scope.data = [];
			
			$scope.$watch('panneau', function() {
        		if ($scope.panneau) {
        			$scope.IName = $scope.panneau.name;
        			$scope.IHeure = new Date($scope.panneau.hourOfDisplay);
        			angular.forEach($scope.data, function(value) {
            			if (value.id === $scope.panneau.flight.id) {
            				$scope.selected = value;
            			}
            		});
        		}
        	});
			
			$scope.refresh = function() {
				if ($scope.data.length === 0) {
					flightAPI.list()
		    		.success(function(data) {
		    			$scope.data = data;
		    			angular.forEach($scope.data, function(value) {
	            			if (value.id === $scope.panneau.flight.id) {
	            				$scope.selected = value;
	            			}
	            		});
		        	})
		        	.error(function() {
						ngToast.create({
							content: 'Erreur de communication avec le serveur',
							className: 'danger'
						});
					});
				}
			};
			
			$scope.$watch('view', function() {
				if ($scope.view === 'tab4') {
					$scope.refresh();
				}
			});
			
			$scope.select = function(o) {
        		if (o === $scope.selected) {
        			$scope.selected = null;
        		} else {
        			$scope.selected = o;
        		}
        	};
        	  
        	$scope.ajout = function() {
        		var panneau = {};
        		panneau.id = $scope.panneau.id;
        		panneau.name = $scope.IName;
        		panneau.hourOfDisplay = $filter('date')($scope.IHeure, $scope.sendFormat);
        		panneau.idFlight = $scope.selected.id;
        		console.log(panneau);
        		panelAPI.modify(panneau)
        		.success(function(data) {
        			ngToast.create({
    					content: 'Le panneau a bien été modifié',
    					className: 'success'
    				});
        			$scope.added = data;
        			$scope.added.hourOfDisplayText = $filter('date')(new Date($scope.added.hourOfDisplay),'HH:mm');
        			console.log($scope.added);
        			
        			delete $scope.IName;
        			$scope.selected = null;
        			$scope.IHeure = new Date();
            	})
            	.error(function() {
    				ngToast.create({
    					content: 'Erreur de communication avec le serveur',
    					className: 'danger'
    				});
    			});
        	};
        },
        templateUrl : 'views/directiveAjoutPanneau.html',
        replace : true
    };
});
